package user_api

import (
	"com.cyt.common/library/encrypt"
	"com.cyt.common/library/util/httputil"
	"github.com/gogf/gf/encoding/gurl"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/os/gtime"
	"github.com/gogf/gf/text/gstr"
	"sort"
	"time"
)

// 用户中心开放系统

func CallApi(ApiName string, params map[string]interface{}) string {
	OpenUrl := g.Cfg().GetString("cyt_crm.open_url", "http://open.91cyt.com/api/call")
	AuthKey := g.Cfg().GetString("cyt_crm.auth_key", "duoxiaoxia.dianba")
	AuthSecret := g.Cfg().GetString("cyt_crm.auth_secret", "FN7GDsNHygjk5aQjIQPc")

	params = Sign(AuthKey, AuthSecret, params)
	urlStr := httputil.BuildMapSort(params)

	response, _ := g.Client().SetTimeout(60*time.Second).SetHeader("open-api-name", ApiName).SetRetry(5, 5*time.Second).DoRequest("POST", OpenUrl+"?"+urlStr)
	return response.ReadAllString()
}

// map 所有key转化成小写
func MapChangeKeyCase(params map[string]interface{}) map[string]interface{} {
	data := make(map[string]interface{}, len(params))
	for k, v := range params {
		key := gstr.ToLower(k)
		data[key] = v
	}
	return data
}

// map 根据key值排序
func MapSortByKey(params map[string]interface{}) map[string]interface{} {
	NewMap := make(map[string]interface{}, len(params))

	var keys []string
	for k, _ := range params {
		keys = append(keys, k)
	}
	sort.Strings(keys)
	for _, key := range keys {
		NewMap[key] = params[key]
	}

	return NewMap
}

func Sign(key, secret string, params map[string]interface{}) map[string]interface{} {
	OpenUrl := g.Cfg().GetString("cyt_crm.open_url", "http://open.91cyt.com/api/call")
	Prefix := g.Cfg().GetString("cyt_crm.auth_version", "auth_")
	AuthVersion := g.Cfg().GetString("cyt_crm.auth_version", "5.1.2")
	params[Prefix+"version"] = AuthVersion
	params[Prefix+"key"] = key
	params[Prefix+"timestamp"] = gtime.Timestamp()

	signMap := MapChangeKeyCase(params)
	authSignature := Signature(signMap, "POST", OpenUrl, secret)
	params["auth_signature"] = authSignature
	return params
}

func Signature(payload map[string]interface{}, method, uri, secret string) string {
	urlStr, _ := gurl.Decode(httputil.BuildMapSort(payload))
	urlSlice := g.SliceStr{method, uri, urlStr}
	urlJoin := gstr.Join(urlSlice, "\n")

	return encrypt.HmacSha256(urlJoin, secret)
}
